import logging
import pickle
import os
import socketserver

# Настройка логгирования
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s: %(message)s')

def load_file(filename):
    packets = []
    chunk_size = 16
    with open(filename, "rb") as file:
        packets.append(pickle.dumps([2, "FS", "output.txt"]))
        while True:
            chunk = file.read(chunk_size)
            if not chunk:
                break
            size = len(chunk)
            header = [2, "FD", size, chunk]
            packets.append(pickle.dumps(header))
        packets.append(pickle.dumps(['END', filename]))
    return packets

class O2S(socketserver.BaseRequestHandler):
    def handle(self):
        logging.info(f"Client {self.client_address[0]} connected")
        try:
            while True:
                data = self.request.recv(1024)
                if not data:
                    break
                packet = pickle.loads(data)
                if packet[0] == "GET":
                    filename = packet[1]
                    logging.info(f"Client {self.client_address[0]} requested {filename}")
                    if os.path.exists(filename):
                        for packet in load_file(filename):
                            self.request.sendall(packet)
                        logging.info(f"Client {self.client_address[0]} recieved {filename}")
                    else:
                        logging.info(f"Client {self.client_address[0]} requested {filename} not founded")
                        self.request.sendall(pickle.dumps(["ERR", "File not found"]))
        finally:
            logging.info(f"Client {self.client_address[0]} disconnected")

if __name__ == "__main__":
    HOST, PORT = "127.0.0.1", 65432
    with socketserver.TCPServer((HOST, PORT), O2S) as server:
        logging.info("Server started at {}:{}".format(HOST, PORT))
        server.serve_forever()